<?php


namespace app\api\model\User;


use think\facade\Db;
use think\Model;

class UserModel extends Model
{

    /**
     * 数据表名
     * @var string
     */
    protected $name = "user";

    /**
     * 根据条件查询单挑数据
     * @param $where
     * @param string $filed
     * @return array|Model|null
     * @throws
     */
    public static function getUserWhere($where,$filed = "*")
    {
        $user = Db::name("user")->field($filed)->where($where)->find();
        return $user;
    }


    /**
     * @param $where
     * @param string $filed
     * @return array|Model|null
     * @throws
     */
    public static function getUserWhereJoin($where,$filed = "u.*")
    {
        $user = Db::name("user")
            ->alias('u')
            ->join('user_wallet uw','uw.uid = u.id')
            ->field($filed)
            ->where($where)->find();
        return $user;
    }

    /**
     * 根据条件查询多条数据
     * @param $where
     * @return mixed
     * @throws
     */
    public static function getUserWhereMore($where)
    {
        $list = Db::name("user")->where($where)->select()->toArray();
        return $list;
    }

    /**
     * 统计总数
     * @param $where
     * @return int
     */
    public static function getUserCountWhere($where)
    {
        $count = Db::name("user")->where($where)->count();
        return $count;
    }

    /**
     * 分页查询
     * @param $page
     * @param $limit
     * @param $where
     * @return mixed
     * @throws
     */
    public static function getUserListWhere($page,$limit,$where = [],$field="*")
    {
        $start = ceil(($page-1)*$limit);
        $list = Db::name('user')->field($field)->where($where)->limit($start,$limit)->select()->toArray();
        return $list;
    }

    /**
     * 添加返回ID
     * @param $data
     * @return int
     */
    public static function addUser($data)
    {
        $id = Db::name('user')->insertGetId($data);
        return $id;
    }

    /**
     * 更新
     * @param $where
     * @param $save
     * @return int
     * @throws
     */
    public static function updateUserWhere($where,$save)
    {
        $flag = Db::name('user')->where($where)->update($save);
        return $flag;
    }

    /**
     * 生成UID
     */
    public static function generateUID()
    {
        $prefix = chr(mt_rand(65, 90));
        do {
            $number = mt_rand(100000, 999999);
            $sn= $prefix . $number;
        } while (!empty(self::where('sn', '=', $sn)->count()));
        return $sn;
    }

}